<template>
  <div class="upload">
    <n-modal
      v-model:show="showModal"
      preset="dialog"
      title="应用上传"
      content="你确认?"
      positive-text="确认"
      @positive-click="submitCallback"
      @negative-click="cancelCallback"
      negative-text="取消"
      :mask-closable="false"
      @close="cancelCallback"
    >
      <div>
        <n-form inline :label-width="80" :model="formData" size="large">
          <n-form-item label="名称" path="data.name">
            <n-input v-model:value="formData.data.name" placeholder="请输入应用名称" />
          </n-form-item>
          <n-form-item label="描述" path="data.description">
            <n-input placeholder="描述" v-model:value="formData.data.description" />
          </n-form-item>
        </n-form>
      </div>
      <n-upload action="" :customRequest="customRequest">
        <n-upload-dragger>
          <div style="margin-bottom: 12px">
            <n-icon size="48" :depth="3">
              <archive-icon />
            </n-icon>
          </div>
          <n-text style="font-size: 16px">点击或者拖动文件到该区域来上传</n-text>
          <n-p depth="3" style="margin: 8px 0 0 0">
            请不要上传敏感数据，比如你的银行卡号和密码，信用卡号有效期和安全码
          </n-p>
        </n-upload-dragger>
      </n-upload>
    </n-modal>
  </div>
</template>

<script setup>
  import { ArchiveOutline as ArchiveIcon } from '@vicons/ionicons5';
  import { useRoute, useRouter } from 'vue-router';
  import { useMessage, useLoadingBar } from 'naive-ui';
  import { uploadFile } from '@/api/apps/app';
  import { ref, unref, defineProps } from 'vue';
  const route = useRoute();
  const router = useRouter();
  const loadingBar = useLoadingBar();
  const props = defineProps({
    showModal: Boolean,
  });
  const message = useMessage();
  const formData = ref({
    data: {
      name: '',
      description: '',
    },
  });
  const fileData = ref({});
  const customRequest = ({ file }) => {
    fileData.value = {
      file: file.file,
    };
  };
  const emit = defineEmits(['update:showModal']);
  const cancelCallback = () => {
    emit('update:showModal', false);
  };
  const submitCallback = () => {
    loadingBar.start();
    formData.value.file = fileData.value.file;
    uploadFile(formData.value)
      .then((res) => {
        loadingBar.finish();
        if (res.data.success) {
          message.success('上传成功');
          emit('update:showModal', false);
          reloadPage();
        } else {
          message.error(res.data.msg);
          emit('update:showModal', false);
        }
      })
      .catch(() => {
        loadingBar.finish();
        message.error('上传失败');
      });
  };

  // 刷新页面
  const reloadPage = () => {
    router.push({
      path: '/redirect' + unref(route).fullPath,
    });
  };
</script>
